package com.bml.architect.netty.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    static  ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 发送消息读取
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.forEach(ch ->{
            if(ch != channel){
                ch.writeAndFlush("[客户端] "+ ch.remoteAddress()  +" "+ dateFormat.format(new Date()) +" 发送了消息:" + msg +"\n" +"_");
            }else{
                ch.writeAndFlush("[自己] "+ch.remoteAddress() +" "+ dateFormat.format(new Date()) +" 发送了消息："+msg +" \n" +"_");
            }
        });

    }

    /**
     *下线了提醒
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[客户端] "+channel.remoteAddress() +" 下线了 "+ dateFormat.format(new Date()) +"\n");
        System.out.println("[客户端]"+channel.remoteAddress()+"下线了 \n");
        System.out.println("下线了，size="+channelGroup.size());
    }

    /**
     * 通道激活
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[客户端] "+channel.remoteAddress()+" 上线了 "+ dateFormat.format(new Date())+"\n");
        channelGroup.add(channel);
        System.out.println(channelGroup.size());
        System.out.println("[客户端] "+channel.remoteAddress()+" 上线了 \n");
    }

}